import { interviewInvitationService } from "../../services/interviewInvitationService";

export class InterviewInvitationPage {
  constructor() {
    this.currentPage = 1;
    this.pageSize = 10;
    this.totalPages = 0;
    this.searchType = "id";
    this.searchValue = "";
  }

  render() {
    const dom = document.createElement("div");
    dom.innerHTML = `
      <section class="section">
        <div class="section-body">
          <div class="row">
            <div class="col-12 col-md-6 col-lg-12">
              <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                  <h4 class="m-0">面试邀请管理</h4>
                  <div class="d-flex align-items-center">
                    <div class="input-group mr-2" style="width: 600px">
                      <select class="form-control" id="searchType" style="width: 50px">
                        <option value="id">ID</option>
                        <option value="companyName">企业名称</option>
                        <option value="seekerName">求职者姓名</option>
                        <option value="seekerEmail">求职者邮箱</option>
                      </select>
                      <input type="text" class="form-control" placeholder="输入搜索内容" id="searchInput" />
                      <div class="input-group-append">
                        <button class="btn btn-primary" type="button" id="searchBtn">
                          <i class="fas fa-search"></i> 查询
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="card-body p-0">
                  <div class="table-responsive">
                    <table class="table table-striped table-md">
                      <thead>
                        <tr>
                          <th>ID</th>
                          <th>邀请标题</th>
                          <th>企业名称</th>
                          <th>求职者姓名</th>
                          <th>求职者邮箱</th>
                          <th>邀请时间</th>
                          <th>操作</th>
                        </tr>
                      </thead>
                      <tbody id="invitationTableBody"></tbody>
                    </table>
                  </div>
                </div>
                <div class="card-footer text-right">
                  <nav class="d-inline-block">
                    <ul class="pagination mb-0" id="pagination"></ul>
                  </nav>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 面试邀请详情模态框 -->
        <div class="modal fade" id="detailModal" tabindex="-1">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">面试邀请详情</h5>
                <button type="button" class="close" id="detailModalClose">
                  <span>&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <div class="form-group">
                  <label>邀请标题</label>
                  <input type="text" class="form-control" id="invitationTitle" readonly />
                </div>
                <div class="form-group">
                  <label>企业名称</label>
                  <input type="text" class="form-control" id="companyName" readonly />
                </div>
                <div class="form-group">
                  <label>企业邮箱</label>
                  <input type="email" class="form-control" id="companyEmail" readonly />
                </div>
                <div class="form-group">
                  <label>联系电话</label>
                  <input type="tel" class="form-control" id="contactPhone" readonly />
                </div>
                <div class="form-group">
                  <label>邀请详情</label>
                  <textarea class="form-control" id="invitationDetails" readonly></textarea>
                </div>
                <div class="form-group">
                  <label>求职者姓名</label>
                  <input type="text" class="form-control" id="seekerName" readonly />
                </div>
                <div class="form-group">
                  <label>求职者邮箱</label>
                  <input type="email" class="form-control" id="seekerEmail" readonly />
                </div>
                <div class="form-group">
                  <label>邀请时间</label>
                  <input type="text" class="form-control" id="invitationTime" readonly />
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
              </div>
            </div>
          </div>
        </div>
      </section>
    `;

    this._bindElements(dom);
    this._bindEvents(dom);
    this.loadData();
    return dom;
  }

  _bindElements(dom) {
    this.searchType = dom.querySelector("#searchType");
    this.searchInput = dom.querySelector("#searchInput");
    this.searchBtn = dom.querySelector("#searchBtn");
    this.invitationTableBody = dom.querySelector("#invitationTableBody");
    this.pagination = dom.querySelector("#pagination");
    this.detailModalClose = dom.querySelector("#detailModalClose");
  }

  _bindEvents(dom) {
    if (this.searchBtn) {
      this.searchBtn.addEventListener("click", () => this._handleSearch());
    }

    if (this.searchInput) {
      this.searchInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
          this._handleSearch();
        }
      });
    }

    if (this.detailModalClose) {
      this.detailModalClose.addEventListener("click", () => {
        $("#detailModal").modal("hide");
      });
    }
  }

  async loadData() {
    try {
      const response = await interviewInvitationService.getInterviewInvitations(
        this.currentPage,
        this.pageSize
      );

      // 处理空响应或数组响应
      if (!response) {
        console.error("Empty response received");
        this._showError("获取数据失败：服务器返回空响应");
        return;
      }

      // 如果响应是数组，转换为期望的格式
      const data = Array.isArray(response)
        ? {
            items: response,
            total: response.length,
            totalPages: Math.ceil(response.length / this.pageSize),
          }
        : response;

      // 检查转换后的数据结构
      if (!data.items) {
        console.error("Invalid response format:", data);
        this._showError("获取数据失败：返回格式不正确");
        return;
      }

      this.totalPages =
        data.totalPages || Math.ceil(data.total / this.pageSize);
      this._renderTable(data.items);
      this._renderPagination();
    } catch (error) {
      console.error("Failed to load interview invitations:", error);
      if (error.response && error.response.status === 401) {
        this._showError("请先登录后再访问");
        // 可以在这里添加重定向到登录页面的逻辑
        window.location.href = "/login";
      } else {
        this._showError("加载面试邀请列表失败");
      }
    }
  }

  _renderTable(invitations) {
    if (!this.invitationTableBody) return;

    if (!invitations || !Array.isArray(invitations)) {
      console.error("Invalid invitations data:", invitations);
      this.invitationTableBody.innerHTML =
        '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
      return;
    }

    if (invitations.length === 0) {
      this.invitationTableBody.innerHTML =
        '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
      return;
    }

    this.invitationTableBody.innerHTML = "";
    invitations.forEach((invitation) => {
      const row = document.createElement("tr");
      row.innerHTML = `
        <td>${invitation.id || "-"}</td>
        <td>${invitation.invitationTitle || "-"}</td>
        <td>${invitation.companyName || "-"}</td>
        <td>${invitation.seekerName || "-"}</td>
        <td>${invitation.seekerEmail || "-"}</td>
        <td>${
          invitation.invitationTime
            ? new Date(invitation.invitationTime).toLocaleString()
            : "-"
        }</td>
        <td>
          <button class="btn btn-info btn-sm view-btn" data-id="${
            invitation.id
          }">
            <i class="fas fa-eye"></i> 查看
          </button>
        </td>
      `;
      this.invitationTableBody.appendChild(row);
    });

    // Add event listeners to view buttons
    this.invitationTableBody.querySelectorAll(".view-btn").forEach((btn) => {
      btn.addEventListener("click", (e) => {
        const id = e.target.closest(".view-btn").dataset.id;
        this._showInvitationDetails(id);
      });
    });
  }

  _renderPagination() {
    if (!this.pagination) return;

    this.pagination.innerHTML = "";
    const maxVisiblePages = 5;
    let startPage = Math.max(
      1,
      this.currentPage - Math.floor(maxVisiblePages / 2)
    );
    let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // Previous button
    const prevLi = document.createElement("li");
    prevLi.className = `page-item ${this.currentPage === 1 ? "disabled" : ""}`;
    prevLi.innerHTML = `
      <a class="page-link" href="#" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    `;
    prevLi.addEventListener("click", (e) => {
      e.preventDefault();
      if (this.currentPage > 1) {
        this.currentPage--;
        this.loadData();
      }
    });
    this.pagination.appendChild(prevLi);

    // Page numbers
    for (let i = startPage; i <= endPage; i++) {
      const pageLi = document.createElement("li");
      pageLi.className = `page-item ${i === this.currentPage ? "active" : ""}`;
      pageLi.innerHTML = `<a class="page-link" href="#">${i}</a>`;
      pageLi.addEventListener("click", (e) => {
        e.preventDefault();
        this.currentPage = i;
        this.loadData();
      });
      this.pagination.appendChild(pageLi);
    }

    // Next button
    const nextLi = document.createElement("li");
    nextLi.className = `page-item ${
      this.currentPage === this.totalPages ? "disabled" : ""
    }`;
    nextLi.innerHTML = `
      <a class="page-link" href="#" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    `;
    nextLi.addEventListener("click", (e) => {
      e.preventDefault();
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.loadData();
      }
    });
    this.pagination.appendChild(nextLi);
  }

  async _showInvitationDetails(id) {
    try {
      const invitation =
        await interviewInvitationService.getInterviewInvitation(id);
      document.getElementById("invitationTitle").value =
        invitation.invitationTitle;
      document.getElementById("companyName").value = invitation.companyName;
      document.getElementById("companyEmail").value = invitation.companyEmail;
      document.getElementById("contactPhone").value = invitation.contactPhone;
      document.getElementById("invitationDetails").value =
        invitation.invitationDetails;
      document.getElementById("seekerName").value = invitation.seekerName;
      document.getElementById("seekerEmail").value = invitation.seekerEmail;
      document.getElementById("invitationTime").value = new Date(
        invitation.invitationTime
      ).toLocaleString();
      $("#detailModal").modal("show");
    } catch (error) {
      console.error("Failed to load invitation details:", error);
      this._showError("加载面试邀请详情失败");
    }
  }

  _handleSearch() {
    this.searchValue = this.searchInput.value.trim();
    this.currentPage = 1;
    this.loadData();
  }

  _showError(message) {
    if (this.invitationTableBody) {
      this.invitationTableBody.innerHTML = `
        <tr>
          <td colspan="7" class="text-center text-danger">
            ${message}
          </td>
        </tr>
      `;
    }
    if (this.pagination) {
      this.pagination.innerHTML = "";
    }
  }
}

// Initialize the page when the DOM is loaded
document.addEventListener("DOMContentLoaded", () => {
  new InterviewInvitationPage();
});
